package com.base.myproject.server;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.base.myproject.server.database.PoolMan;


/**
 * @author cxghiu410@gmail.com
 *	用于接收上传的文件，并更新数据库相关的字段。
 */
public class UploadFileServlet extends HttpServlet {

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setFileCleaningTracker(FileCleanerCleanup
				.getFileCleaningTracker(getServletContext()));

		ServletFileUpload upload = new ServletFileUpload(factory);
		String fileName = null;
		
		String uploadFile = null;
		String fileDir = null;
		
		String action = req.getParameter("action");
		
		String uploadPath = getServletContext().getRealPath("/");//获取文件路径

		try {
			List<FileItem> items = upload.parseRequest(req);
			for (final FileItem item : items) {
				if (!item.isFormField()) {
					fileName = item.getName();
					int start = fileName.lastIndexOf(".");
					File file = null;
					uploadFile = fileName.substring(0, start) + System.currentTimeMillis() + fileName.substring(start);
					if (action.equals("update")) {
						fileDir = uploadPath + "upload" + File.separator + req.getParameter("file");
						file = new File(fileDir, uploadFile);
					} else {
						fileDir = uploadPath + req.getParameter("file");
						file = new File(fileDir, fileName);
					}
					if (!new File(fileDir).exists()) {
						new File(fileDir).mkdirs();
					}
					item.write(file);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		PoolMan pm = new PoolMan();  //一个工具类，用于连接数据库
		Connection conn = pm.getConnection("test");
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
			String sql = "";
			if (action.equals("update")) {
				sql = "update " + req.getParameter("table") + " set uploadFile = '"
				+ fileDir + File.separator + uploadFile
				+ "', uploadFileName = '"
				+ fileName
				+ "' where icode in (select max(icode) from " + req.getParameter("table") + ")";
			} else if (action.equals("insert")) {
				sql = "insert " + req.getParameter("table") + "(bcode, bcodeimagepath) values('"
				+ req.getParameter("bcode")
				+ "', '"
				+ req.getParameter("file") + File.separator + fileName + "')";
				String deleteSql = "delete " + req.getParameter("table") + " where bcode = '" + req.getParameter("bcode") + "'";
				stmt.executeUpdate(deleteSql);
			}
			stmt.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(stmt != null) stmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}
	}

}
